package com.party.core.service.member.impl;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.common.paging.Page;
import com.party.core.dao.read.member.PartnerMemberReadDao;
import com.party.core.dao.write.member.PartnerMemberWriteDao;
import com.party.core.model.BaseModel;
import com.party.core.model.member.Member;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.system.RoleEnum;
import com.party.core.model.system.SysConfig;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.system.ISysConfigService;
import com.party.core.service.system.ISysRoleService;
import com.sun.istack.NotNull;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 合作商会员关系
 * Created by wei.li
 *
 * @date 2017/9/20 0020
 * @time 14:55
 */

@Service
public class PartnerMemberService implements IPartnerMemberService {

    @Autowired
    private PartnerMemberReadDao partnerMemberReadDao;

    @Autowired
    private PartnerMemberWriteDao partnerMemberWriteDao;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysConfigService sysConfigService;

    /**
     * 插入合作商会员关系
     * @param partnerMember 合作商会员
     * @return 编号
     */
    @Override
    public String insert(PartnerMember partnerMember) {
        BaseModel.preInsert(partnerMember);
        boolean result = partnerMemberWriteDao.insert(partnerMember);
        if (result){
            return partnerMember.getId();
        }
        return null;
    }

    /**
     * 插入合作商会员
     * @param partnerId 机构编号
     * @param memberId 会员编号
     */
    @Override
    public void insert(String partnerId, String memberId) {
        PartnerMember partnerMember = new PartnerMember(partnerId, memberId);
        PartnerMember mainOrg = this.getMainOrg(memberId, partnerId);
        if (mainOrg == null) {
            partnerMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
        }
        try {
            this.insert(partnerMember);
        } catch (DuplicateKeyException e) {
        }
    }

    /**
     * 插入合作商会员
     * @param partnerId 机构编号
     * @param memberId 会员编号
     * @param createDate 创建时间
     */
    @Override
    public void insert(String partnerId, String memberId, Date createDate) {
        PartnerMember partnerMember = new PartnerMember(partnerId, memberId, createDate);
        try {
            this.insert(partnerMember);
        } catch (DuplicateKeyException e) {
        }
    }

    /**
     * 更新合作商会员关系
     * @param partnerMember 合作商会员关系
     * @return 编号
     */
    @Override
    public boolean update(PartnerMember partnerMember) {
        partnerMember.setUpdateDate(new Date());
        return partnerMemberWriteDao.update(partnerMember);
    }

    /**
     * 逻辑删除
     * @param id 实体主键
     * @return 删除结果（true/false）
     */
    @Override
    public boolean deleteLogic(@NotNull String id) {
        if (Strings.isNullOrEmpty(id)){
            return false;
        }
        return partnerMemberWriteDao.deleteLogic(id);
    }

    /**
     * 物理删除
     * @param id 实体主键
     * @return 删除结果（true/false）
     */
    @Override
    public boolean delete(@NotNull String id) {
        if (Strings.isNullOrEmpty(id)){
            return false;
        }
        return partnerMemberWriteDao.delete(id);
    }

    /**
     * 批量逻辑删除
     * @param ids 主键集合
     * @return 删除结果（true/false）
     */
    @Override
    public boolean batchDeleteLogic(@NotNull Set<String> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return false;
        }
        return partnerMemberWriteDao.batchDeleteLogic(ids);
    }

    /**
     * 批量物理删除
     * @param ids 主键集合
     * @return 删除结果（true/false）
     */
    @Override
    public boolean batchDelete(@NotNull Set<String> ids) {
        if (CollectionUtils.isEmpty(ids)){
            return false;
        }
        return partnerMemberWriteDao.batchDelete(ids);
    }

    /**
     * 根据编号获取
     * @param id 主键
     * @return 合作商会员关系
     */
    @Override
    public PartnerMember get(String id) {
        return partnerMemberReadDao.get(id);
    }

    /**
     * 分页查询
     * @param partnerMember 合作商会员
     * @param page 分页信息
     * @return 合作商会员列表
     */
    @Override
    public List<PartnerMember> listPage(PartnerMember partnerMember, Page page) {
        return partnerMemberReadDao.listPage(partnerMember, page);
    }

    /**
     * 合作商会员所有列表
     * @param partnerMember 合作商会员
     * @return 所有列表
     */
    @Override
    public List<PartnerMember> list(PartnerMember partnerMember) {
        return partnerMemberReadDao.listPage(partnerMember, null);
    }

    @Override
    public List<PartnerMember> batchList(@NotNull Set<String> ids, PartnerMember partnerMember, Page page) {
        return null;
    }

    /**
     * 如果没有则设置
     * @param partnerMember 机构会员
     * @return 机构会员
     */
    @Override
    public PartnerMember getSet(PartnerMember partnerMember) {
        Long count = this.getCount(partnerMember);
        if (new Long(0).equals(count)) {
            boolean hasZxgsPartner = hasZxgsPartner(partnerMember.getPartnerId(), partnerMember.getMemberId());
            if (!hasZxgsPartner) {
                PartnerMember mainOrg = this.getMainOrg(partnerMember.getMemberId(), partnerMember.getPartnerId());
                if (mainOrg == null) {
                    partnerMember.setPartnerType(PartnerMember.IS_MAIN_TYPE);
                    this.insert(partnerMember);
                    return partnerMember;
                }
            }
        }
        return null;
    }

    /**
     * 统计机构会员
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @param partnerId 机构编号
     * @return 统计数据
     */
    @Override
    public List<HashMap<String, Object>> countByDate(String startDate, String endDate, String partnerId, Boolean isRealName) {
        HashMap<String, Object> parameter = Maps.newHashMap();
        parameter.put("startDate", startDate);
        parameter.put("endDate", endDate);
        parameter.put("partnerId", partnerId);
        parameter.put("isRealName", isRealName);
        return partnerMemberReadDao.countByDate(parameter);
    }

    /**
     * 统计机构数据
     * @param partnerId 机构编号
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return 统计数据
     */
    @Override
    public Integer count(String partnerId, String startDate, String endDate, Boolean isRealName) {
        HashMap<String, Object> parameter = Maps.newHashMap();
        parameter.put("startDate", startDate);
        parameter.put("endDate", endDate);
        parameter.put("partnerId", partnerId);
        parameter.put("isRealName", isRealName);
        return partnerMemberReadDao.count(parameter);
    }

    /**
     * 统计机构数据
     * @param partnerId 机构编号
     * @param isRealName 是否实名用户
     * @return 统计数据
     */
    @Override
    public Integer count(String partnerId, Boolean isRealName) {
        return this.count(partnerId, null, null, isRealName);
    }

    /**
     * 获取机构下的所有会员
     * @param partnerId
     * @return
     */
    public List<Member> getMembersByPartnerId(String partnerId) {
        return partnerMemberReadDao.getMembersByPartnerId(partnerId);
    }

    /**
     * 通过机构id和用户id查找
     * @param partnerId
     * @param memberId
     * @return
     */
    @Override
    public PartnerMember findByPartnerAndMember(String partnerId, String memberId) {
        PartnerMember partnerMember = new PartnerMember(partnerId, memberId);
        List<PartnerMember> list = listPage(partnerMember, null);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public Long getCount(PartnerMember partnerMember) {
        return partnerMemberReadDao.getCount(partnerMember);
    }

    @Override
    public PartnerMember getMainOrg(String memberId, String partnerId) {
        //获取主账号id
        String partnerId1 = memberGroupService.getPartnerId(partnerId);
        return partnerMemberReadDao.getMainOrg(memberId, partnerId1);
    }

    @Override
    public List<PartnerMember> getMemberPartners(PartnerMember partnerMember) {
        return partnerMemberReadDao.getMemberPartners(partnerMember);
    }

    /***
     * 获取用户机构_to
     * @Date 9:22 2019/11/15
     * @param param
     * @return
     **/
    @Override
    public List<PartnerMember> getMemberPartnersTo(Map<String, Object> param) {
        return partnerMemberReadDao.getMemberPartnersTo(param);
    }

    private boolean hasZxgsPartner(String partnerId,String memberId) {
        boolean result = false;

        boolean b = sysRoleService.hasRole(partnerId, RoleEnum.KNOWING_COMMUNE_ROLE.getCode());
        if (!b) {
            return result;
        } else {
            String xzgsMemberId = "";
            SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
            if (xzgsConfig == null) {
                //正式环境中行知公社机构ID
                xzgsMemberId = "c94e89415d7d4611b706cecfc43af2ae";
            } else {
                xzgsMemberId = xzgsConfig.getValue();
            }
            HashMap<String, Object> params = Maps.newHashMap();

            List<String> orgIds = memberGroupService.getChild(xzgsMemberId);

            params.put("memberId",memberId);
            params.put("partnerIds",orgIds);
            List<PartnerMember> partners = partnerMemberReadDao.getMemberPartnersTo(params);

            if (partners.size() > 0) {
                result = true;
            } else {
                result = false;
            }
            return result;
        }
    }

    @Override
    public Integer cAnalysisGetMemberCount(List<String> partnerIds, Map<String,Object> params) {
        return partnerMemberReadDao.cAnalysisGetMemberCount(partnerIds,params);
    }

    @Override
    public Integer getMemberRecommendCount(List<String> partnerIds,Map<String,Object> params) {
        return partnerMemberReadDao.getMemberRecommendCount(partnerIds,params);
    }

    @Override
    public List<PartnerMember> getAllXzgsMember(Map<String, Object> params) {
        return partnerMemberReadDao.getAllXzgsMember(params);
    }
}
